package com.abo.yaas.view.widgets.panels;

import com.abo.yaas.domain.User;
import com.abo.yaas.i18n.Lang;
import com.abo.yaas.i18n.LocaleChangeListener;
import com.abo.yaas.i18n.LocaleChangedEvent;
import com.abo.yaas.view.AbstractView;
import com.abo.yaas.view.ViewAction;
import com.abo.yaas.view.widgets.forms.UserForm;
import com.vaadin.data.util.BeanItem;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Panel;
import com.vaadin.ui.VerticalLayout;

@SuppressWarnings("serial")
public class UserFormPanel extends AbstractView<VerticalLayout> implements
        LocaleChangeListener {
    private final UserForm form = new UserForm();

    private final VerticalLayout layout;

    private final Panel panel;

    public UserFormPanel() {
        super(new VerticalLayout());
        layout = getContent();
        layout.setSizeUndefined();
        layout.setWidth("100%");
        layout.setMargin(true);
        panel = new Panel();
        panel.setWidth("450px");
        panel.addComponent(form);
        layout.addComponent(panel);
        layout.setComponentAlignment(panel, Alignment.MIDDLE_CENTER);
        Lang.addListener(this);
    }

    @Override
    public void activated(Object... params) {
        User user = null;
        for (final Object param : params) {
            if (param instanceof User) {
                user = (User) param;
            } else if (param instanceof ViewAction) {
                final String caption = param.equals(ViewAction.VA_EDIT_USER) ? Lang
                        .getMessage("EDIT_DATA") : Lang
                        .getMessage("CREATE_USER");

                panel.setCaption(caption);
                form.setIsEdditing(param.equals(ViewAction.VA_EDIT_USER));
            }
        }
        if (user == null) {
            user = new User();
        }
        form.setItemDataSource(new BeanItem<User>(user));
    }

    @Override
    public void deactivated(Object... params) {

    }

    @Override
    public void localeChanged(LocaleChangedEvent event) {
        final String caption = form.getIsEdditing() ? Lang.getMessage("EDIT_DATA") : Lang.getMessage("CREATE_USER");

        panel.setCaption(caption);
        if (form.getItemDataSource() != null) {
            form.setItemDataSource(form.getItemDataSource());
        }
    }
}
